#include "graphicsplugin.h"
#include <QtGui>
#include <QObject>
#include <QtTest>
#include <QThread>
#include "playall.h"
#include "settings.h"

QSqlDatabase Querier::database;

GraphicsPlugin::GraphicsPlugin(QWidget * parent) : KeyControllableMenu(parent), ui(new Ui::GraphicsPlugin)
{
    setMaximumSize(QApplication::desktop()->screen(0)->size());
    ui->setupUi(this);
    WindowManager(ui->centralWidget,ui->home,ui->back);
    WindowManager::showWidget(ui->defaultWidget);
    ui->home->setEnabled(false);
    ui->back->setEnabled(false);
    ui->nowPlaying->setEnabled(false);
    ui->nowPlaying->hide();
    volumeDisplay=new VolumeDisplay(ui->widget);
    QSqlQueryModel * result=Querier::getModel("SELECT * FROM MainSettings WHERE settingName='volume'");
    volumeDisplay->setVolume(result->record(0).value("value").toInt());
    //ui->logo->setPixmap(QPixmap(":/imgs/Logo.png"));
    //connect(timer, SIGNAL(timeout()), this, SLOT(hideMouse()));
    connect(ui->volumeUp, SIGNAL(clicked()), volumeDisplay, SLOT(increaseVolume()));
    connect(ui->volumeDown,SIGNAL(clicked()),volumeDisplay,SLOT(decreaseVolume()));
    connect(ui->mute,SIGNAL(clicked()),volumeDisplay,SLOT(mute()));
    PlayerManager::setManager(new PlayerManager());
    PlayerManager::setMainWidget(this);
    PlayerManager::setCentralWidget(ui->centralWidget);
    PlayerManager::setNowPlaying(ui->nowPlaying);
    PlayerManager::setPlayButton(ui->playButton);
    PlayerManager::setStopButton(ui->stopButton);
    PlayerManager::setFastforwardButton(ui->fastforwardButton);
    PlayerManager::setRewindButton(ui->rewindButton);
    PlayerManager::setSkipButton(ui->skipButton);
    PlayerManager::setPreviousButton(ui->previousButton);
    PlayerManager::setRepeatButton(ui->repeat);
    PlayerManager::setShuffleButton(ui->shuffle);
    PlayerManager::setTop(ui->topBar);
    PlayerManager::setBottom(ui->playbackControls_2);
    PlayerManager::setMuteButton(ui->mute);
    PlayerManager::setSliderHolder(ui->sliderHolder);
    Phonon::SeekSlider * slider=new Phonon::SeekSlider(this);
    PlayerManager::setSlider(slider);
    ui->sliderLayout->addWidget(slider);
    slider->setVisible(false);
    mainWidget=ui->defaultWidget;
    mainWidget->setMouseTracking(true);
    ui->centralWidget->setMouseTracking(true);
    KeyBindings::loadKeyBindings();
    parentWidget=parent;
    //setStyleSheet("");
    ui->widget->setAutoFillBackground(true);
    QPalette palette;
    palette.setBrush(QPalette::Window, QBrush(QImage(":/imgs/3F00WaterBackground.png")));
    ui->widget->setPalette(palette);
    ui->widget->repaint();
    ui->widget->setMouseTracking(true);

    setFocusPolicy(Qt::WheelFocus);
    setMouseTracking(true);
    timer=new QTimer(this);
    timer->setSingleShot(true);

    volumeDisplay->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    volumeDisplay->move(parent->width(),100);
    QString selectedButtonStylesheet="QPushButton { background: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(0, 0, 0, 255), stop:0.05 rgba(14, 8, 73, 255), stop:0.36 rgba(28, 17, 145, 255), stop:0.6 rgba(126, 14, 81, 255), stop:0.75 rgba(234, 11, 11, 255), stop:0.79 rgba(244, 70, 5, 255), stop:0.86 rgba(255, 136, 0, 255), stop:0.935 rgba(239, 236, 55, 255)); border: 0px;  }";
    QString unSelectedButtonStyleSheet="QPushButton { border: 0px; color: rgba(0,0,0,0);  background: rgba(0,0,0,0); background-color: rgba(0,0,0,0)  }";
    //setStyleSheets(selectedButtonStylesheet,unSelectedButtonStyleSheet);
    settingsManager=new Settings();
   // ui->centralWidget->layout()->addWidget(settingsManager->getInterface());
    //settingsManager->getInterface()->hide();

    grabKeyboard();
    ThemeSettings::setWidget(ui->widget);
    ui->back->setEnabled(false);
    //setBackButton(ui->back);
    ui->home->setEnabled(false);
    //setHomeButton(ui->home);
    show();    

}

QString GraphicsPlugin::getName() const {
    return "Graphics";
}

void GraphicsPlugin::addWidget(QWidget * widget)  {
    //mainLayout->addWidget(widget);
}

void GraphicsPlugin::addButton(Button * label) {
    //label->setGeometry(0,0,300,200);
    label->setIconSize(QSize(256,80));
    addRow(label);
    /*label->setStyleSheet(unSelectedButtonStyleSheet);

    if(!current) {
        current = label;
        label->setStyleSheet(selectedButtonStylesheet);
        label->setFlat(false);
    }*/
    //buttons.append(label);
    label->setMouseTracking(true);
    ui->plugins_2->addWidget(label,0,Qt::AlignTop);
}

void GraphicsPlugin::setMainPlugins(QList<MenuItemInterface *> * plugins) {
    mainPlugins=plugins;
    //buttons.clear();

    foreach(MenuItemInterface * item, *plugins) {
        FileSelectionInterface * interface = qobject_cast<FileSelectionInterface *>(item);
        Button * label;
        if(interface) {
            PlayerManager::addSelector(interface);
            SelectionTypeMenu * menuItem=new SelectionTypeMenu(this,interface);
           // ui->centralWidget->layout()->addWidget(menuItem);
            //menuItem->hide();
            label=new Button(item->getImage(),"",this,menuItem);
        }
        addButton(label);
    }

    Button * label =new Button(settingsManager->getImage(),"", this, settingsManager->getInterface());
    addButton(label);


}

void GraphicsPlugin::keyPressEvent ( QKeyEvent * event ) {

    //qDebug() <<"keys pressed "<<event->key()<<" "<<event->modifiers();


    /*if(KeyBindings::matchesKeys(KeyBindings::downKey,event)) {
        int index=buttons.indexOf(current);
        if(index+1<buttons.size()) {
            setActive(buttons.at(index+1));
        } else {
            setActive(buttons.at(0));
        }
    } else if(KeyBindings::matchesKeys(KeyBindings::upKey,event)) {
        int index=buttons.indexOf(current);
        if(index-1>=0) {
            setActive(buttons.at(index-1));
        } else {
            setActive(buttons.at(buttons.size()-1));
        }
    }
    else if(KeyBindings::matchesKeys(KeyBindings::selectKey,event)) {
        buttonSelected();
    }*/
    KeyControllableMenu::keyPressEvent(event);

}

void GraphicsPlugin::mouseMoveEvent(QMouseEvent * event) {
    //showMouse();
}

/*void GraphicsPlugin::enterEvent(QEvent * event) {
    showMouse();

    //grabKeyboard();
}*/

void GraphicsPlugin::showMouse() {
    timer->stop();
    QApplication::setOverrideCursor(Qt::ArrowCursor);
    ui->topBar->show();
    ui->playbackControls_2->show();
    //timer->start(7*1000);
}

void GraphicsPlugin::hideMouse() {
//    ui->topBar->hide();
//    ui->playbackControls_2->hide();
//    QApplication::setOverrideCursor(Qt::BlankCursor);
}

void GraphicsPlugin::buttonSelected() {
    ui->defaultWidget->hide();
    WindowManager::showWidget(qobject_cast<QWidget *>(getCurrentButton()->getItem()));
}

void GraphicsPlugin::on_close_clicked()
{
    Querier::getResult("UPDATE MainSettings SET value='"+QString::number(volumeDisplay->getVolume())+"' WHERE settingName='volume'");
    //PlayerManager::stop();
    QTest::qWait(500);
    QApplication::exit(0);
}

void GraphicsPlugin::close()
{
    Querier::getResult("UPDATE MainSettings SET value='"+QString::number(volumeDisplay->getVolume())+"' WHERE settingName='volume'");
    PlayerManager::stop();

    //QTest::qWait(500);
    QApplication::quit();
}

void GraphicsPlugin::on_back_clicked()
{
    WindowManager::goBack();

}

void GraphicsPlugin::on_home_clicked()
{
    WindowManager::goHome();
}

void GraphicsPlugin::test() {
    int volume=volumeDisplay->getVolume()+1;
    if(volume>100)
        volume=100;
    QTest::mouseClick( ui->volumeUp, Qt::LeftButton);
    QCOMPARE(volume,volumeDisplay->getVolume());
    QTest::qWait(3000);
    QTest::keyPress(this, KeyBindings::volumeUpKey[0],(Qt::KeyboardModifier)KeyBindings::volumeUpKey[1]);
    volume++;
    if(volume>100)
        volume=100;
    QCOMPARE(volume,volumeDisplay->getVolume());

    QTest::qWait(3000);
    QTest::mouseClick( ui->volumeDown, Qt::LeftButton);
    volume--;
    QCOMPARE(volume,volumeDisplay->getVolume());

    QTest::qWait(3000);

    QTest::keyPress(this, KeyBindings::volumeDownKey[0],(Qt::KeyboardModifier)KeyBindings::volumeDownKey[1]);
    volume--;
    QCOMPARE(volume,volumeDisplay->getVolume());



    //test the settings menus
    qDebug() <<"plugin count "<<ui->defaultWidget->children().size();

    Button * button=findButton(settingsManager->getInterface());
    if(button) {
        QTest::mouseMove(button);
        emit buttonEntered(button); //hack to make it select in OS X
        QTest::qWait(1000);

        QTest::mouseClick(button, Qt::LeftButton);
        settingsManager->test();
    }

    //QTest::mouseClick( settingsManager->getInterface(), Qt::LeftButton);

    //



    QTest::qWait(2000);
}


void GraphicsPlugin::on_mute_clicked()
{
    if(!KeyControllableMenu::volumeDisplay->isMute()) {
        ui->mute->setIcon(QIcon(":/imgs/3F00Button_Mute.png"));
    } else {
        ui->mute->setIcon(QIcon(":/imgs/3F00Button_Unmute.png"));
    }
}

void GraphicsPlugin::on_nowPlaying_clicked()
{
    /*if(ui->nowPlaying->isVisible()) {
        foreach(QWidget * widget,KeyControllableMenu::queue) {
            KeyControllableMenu * menu=qobject_cast<KeyControllableMenu *>(widget);
            if(menu) {
                QTimer::singleShot(1,menu,SLOT(hide())); //call the slot so it calls the graphicsplugin hide
            } else {
                widget->hide();
            }
        }
        QWidget * player =PlayerManager::getCurrentPlayer();

        KeyControllableMenu::queue.append(player);
        //player->setMinimumHeight(height()-ui->topBar->height()-ui->playbackControls_2->height());
        player->showMaximized();
    }*/
    WindowManager::goToNowPlaying();
}

void GraphicsPlugin::show() {
    KeyControllableMenu::show();

    mainWidget->show();
    grabKeyboard();
}

void GraphicsPlugin::hide() {
    mainWidget->hide();
}

void GraphicsPlugin::on_shuffle_clicked()
{
    PlayerManager::shuffleClicked();
}

void GraphicsPlugin::on_repeat_clicked()
{
        PlayerManager::repeatClicked();
}

void GraphicsPlugin::closeEvent(QCloseEvent * event) {
    Querier::getResult("UPDATE MainSettings SET value='"+QString::number(volumeDisplay->getVolume())+"' WHERE settingName='volume'");
    PlayerManager::stop();
    QTest::qWait(500);
    QApplication::quit();
}
